<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 评论
 *
 * @author      Eden
 * @datetime    2016/12/9 00:43
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
class Commentlist_Model extends API_Model
{

    const PAGE_SIZE = 20;

    private $total = 0;

    /**
     * 参数
     * @var array
     */
    private $params = array();

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主函数
     * @param array $params
     */
    public function run(Array $params)
    {
        $this->params = $params;
        $send['state'] = false;
        do {

            if (!$this->_checkParams()) {
                $send['error'] = $this->getError();
                break;
            }

            $page = $this->input->get('page');
            $page = $page > 0 ? intval($page) : 1;
            $offset = ($page - 1) * self::PAGE_SIZE;

            // 检查 BBSID是否有效
            if (!$this->_checkBbsExists($params['bbsId'])) {
                $send['error'] = '未找到相关主题';
                break;
            }

            $return = array(
                'total' => 0,
                'data' => [],
                'nextPage' => false,
            );
            $lists = $this->_getLists($params['bbsId'], $offset, self::PAGE_SIZE);
            if ($lists) {
                $return['total'] = intval($this->total);
                $return['data'] = $lists;
                $return['nextPage'] = ($offset + self::PAGE_SIZE) < $this->total;
            }

            $send['state'] = true;
            $send['data'] = $return;
        } while(false);
        $this->output->send($send);
    }

    /**
     * 获取列表
     * @param $bbsId
     * @param $offset
     * @param $limit
     * @return array|bool
     */
    private function _getLists($bbsId, $offset, $limit)
    {
        $tdb = clone($this->db);
        $where = array(
            'status' => 1,
            'bbsId' => $bbsId
        );
        $this->total = $tdb->count_all_results('bbs_comments');
        if (empty($this->total)) {
            return false;
        }

        $cdb = clone($this->db);
        $query = $cdb->select('id, userId, text, created')
            ->from('bbs_comments')
            ->where($where)
            ->limit($limit, $offset)
            ->order_by('created', 'DESC')
            ->get();
        $lists = $query->result_array();
        if (empty($lists)) {
            $this->total = 0;
            return false;
        }

        $userIds = array();
        $ids = array();
        if (is_array($lists)) foreach($lists as $list) {
            $id = $list['id'];
            $userId = $list['userId'];
            array_push($ids, $id);
            array_push($userIds, $userId);
        }

        $replys = $this->getReply($ids);

        if (!empty($replys)) foreach ($replys as $reply) {
            $userId = $reply['userId'];
            array_push($userIds, $userId);
        }
        $userInfo = $this->_getUserInfo($userIds);

        $replyInfo = array();
        foreach($replys as $reply) {
            $userId = $reply['userId'];
            $commentId = $reply['commentId'];
            $repData = array();
            $repData['replyId'] = intval($reply['id']);
            $repData['content'] = $reply['content'];
            $repData['created'] = formateTimeStamp($reply['created']);
            $repData['userId'] = intval($reply['userId']);
            $repData['nickName'] = value($userInfo, array($userId, 'nickName'), '');
            $repData['avatar'] = value($userInfo, array($userId, 'avatar'), '');
            $replyInfo[$commentId] = $repData;
        }

        $returns = array();
        foreach ($lists as $list) {
            $cId = $list['id'];
            $uId = $list['userId'];
            $nickName = value($userInfo, array($uId, 'nickName'), '');
            $avatar = value($userInfo, array($uId, 'avatar'), '');
            $returns[] = array(
                'commentId' => intval($cId),
                'nickName' => !empty($nickName) ? $nickName : '',
                'avatar' => !empty($avatar) ? $avatar : '',
                'text' => $list['text'],
                'created' => formateTimeStamp($list['created']),
                'reply' => !empty($replyInfo[$cId]) ? $replyInfo[$cId] : new stdClass()
            );
        }

        return $returns;
    }

    /**
     * 获取用户数据
     * @param array $userIds
     * @return array|bool
     */
    private function _getUserInfo(Array $userIds)
    {
        $userInfo = array();
        $userDb = clone($this->db);
        $query = $userDb->select('u.id, u.nickName, up.avatar')
            ->from('user as u')
            ->where_in('u.id', $userIds)
            ->join('user_profile as up', 'up.userId = u.id')
            ->get();
        $result = $query->result_array();
        if (empty($result)) {
            return $userInfo;
        }

        if (is_array($result)) foreach($result as $item) {
            $userid = $item['id'];
            $info['avatar'] = thumb($item['avatar'], 100, 100);
            $info['nickName'] = $item['nickName'];
            $userInfo[$userid] = $info;
        }
        return $userInfo;
    }

    /**
     * 所有回复
     * @param $ids
     * @return mixed
     */
    private function getReply($ids)
    {
        $replyDb = clone($this->db);
        $query = $replyDb->select('id, commentId, userId, content, created')
            ->where_in('commentId', $ids)
            ->from('bbs_comments_reply')
            ->get();
        $result = $query->result_array();
        return $result;
    }

    /**
     * 检查参数
     * @return bool
     */
    private function _checkParams()
    {
        if (empty($this->params['bbsId'])) {
            $this->setError('参数错误');
            return false;
        }
        return true;
    }

}